package ast.module;

import icg.EQLabel;
import icg.Quadruple;

import java.util.Vector;

import ts.SymbolTable;

import ast.Node;
import ast.decl.Declaration;
import ast.stmt.Statement;
import ast.type.Type;

public class Module {
	private Integer id;
	private Vector<Declaration> listDecl;
	private Statement seq;

	public Module(Integer id, Vector<Declaration> listDecl, Statement seq) {
		this.id = id;
		this.listDecl = listDecl;
		this.seq = seq;

	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < listDecl.size(); i++)
			sb.append(listDecl.elementAt(i).toString()).append("\n");
		return "<Module id=\"" + id + "\">\n" + "<ListDecl>\n" + sb.toString()
				+ "\n</ListDecl>\n" + "<SeqStmt>\n" + seq.toString()
				+ "\n</SeqStmt>\n" + "</Module>";
	}

	public void typeCheck() {
		for (int i = 0; i < listDecl.size(); i++)
			listDecl.elementAt(i).typeCheck();
		seq.typeCheck(Type.VOID);
		if (seq.hasCtrlFlow()) {
			System.out
					.println("statement of control flow must be in a repetition statement");
			SymbolTable.errors++;
		}
		if (seq.isReturned()) {
			System.out.println("return command must be only in a function");
			SymbolTable.errors++;
		}
	}

	public void genCode() {
		for (Declaration d : listDecl)
			d.genCode();
		Node.icg.newQuadrupleTable(id);
		seq.genCode();
		if (EQLabel.pending()!=null) {
			Node.icg.gen(Quadruple.nop());
		}
	}
}
